import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:camera_platform_interface/camera_platform_interface.dart';
import 'dart:ui' as ui;
import '../../event/user_id_event.dart';
import '../../http/api.dart';
import '../../main.dart';
import '../../socket/socket_manager.dart';
import '../../util/camera_util.dart';
import '../../util/toast_util.dart';
import '../auth_clipper.dart';

class AuthModel{

  RxString authType = RxString('0');
  String auth =  settingEntity.auth??'1';
  SocketManager manager = SocketManager();
  String token = '';

  CameraUtil camera = CameraUtil();

  _getToken() async {
    token = await getToken(settingEntity.clientId,settingEntity.clientSecret,settingEntity.username,settingEntity.password,settingEntity.grantType);
    print(token);
  }

  show({int height = 620,int marginTop = 150,int buttonMarginTop = 50}){
    if(settingEntity.norms == '32'){
      return show32(height: height,marginTop: marginTop,buttonMarginTop: buttonMarginTop);
    }else{
      return show21(height: height,marginTop: marginTop,buttonMarginTop: buttonMarginTop);
    }
  }

  show21({int height = 620,int marginTop = 150,int buttonMarginTop = 50}){
    if( authType.value == '0'){
      authType.value = settingEntity.auth!.substring(0,1);
    }
    _onTap(authType.value);
    return Obx(() => Container(
      margin: EdgeInsets.only(top: 10.h,left: 16.w,right: 16.w,bottom: 10.h),
      padding: EdgeInsets.all(30.r),
      width: double.infinity,
      height: height.h,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.all(Radius.circular(4.r)),
      ),
      child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                if(auth.contains('1'))...[
                  Padding(
                      padding: EdgeInsets.only(left: 10.w,right: 10.w),
                      child: InkWell(
                          onTap: (){
                            if(authType.value != '1'){
                              _onTap('1');
                            }
                          },
                          child: Image.asset("assets/images/${authType.value == '1'?'reader_select':'reader_unselect'}.png",width:50.w,fit: BoxFit.fitWidth,)
                      )
                  )
                ],
                if(auth.contains('2'))...[
                  Padding(
                      padding: EdgeInsets.only(left: 10.w,right: 10.w),
                      child: InkWell(
                          onTap: (){
                            if(authType.value != '2'){
                              _onTap('2');
                            }
                          },
                          child: Image.asset("assets/images/${authType.value == '2'?'id_select':'id_unselect'}.png",width:50.w,fit: BoxFit.fitWidth,)
                      )
                  )
                ],
                if(auth.contains('3'))...[
                  Padding(
                      padding: EdgeInsets.only(left: 10.w,right: 10.w),
                      child: InkWell(
                          onTap: (){
                            if(authType.value != '3'){
                              _onTap('3');
                            }
                          },
                          child: Image.asset("assets/images/${authType.value == '3'?'face_select':'face_unselect'}.png",width:50.w,fit: BoxFit.fitWidth,)
                      )
                  )
                ],
                if(auth.contains('4'))...[
                  Padding(
                      padding: EdgeInsets.only(left: 10.w,right: 10.w),
                      child: InkWell(
                          onTap: (){
                            if(authType.value != '4'){
                              _onTap('4');
                            }
                          },
                          child: Image.asset("assets/images/${authType.value == '4'?'qr_select':'qr_unselect'}.png",width:50.w,fit: BoxFit.fitWidth,)
                      )
                  )
                ]
              ],
            ),
            if(authType.value == '1')...[
              Column(
                children: [
                  SizedBox(height: 50.h,),
                  Text("读者卡认证",style: TextStyle(color: Colors.blueAccent,fontSize: 16.sp,fontWeight: FontWeight.bold),),
                  SizedBox(height: 5.h,),
                  Text("请在读卡区域放置您的读者卡",style: TextStyle(color: Colors.blueAccent,fontSize: 12.sp,fontWeight: FontWeight.bold),),
                  SizedBox(height: 20.h,),
                  Stack(
                    alignment: AlignmentDirectional.center,
                    children: [
                      Image.asset("assets/images/mode.png",width:150.w,fit: BoxFit.fitWidth,),
                      Positioned(
                        top: 220.h,
                        right: 0,
                        child: Image.asset("assets/images/reader_mode.png",width:70.w,fit: BoxFit.fitWidth,),
                      )
                    ],
                  )
                ],
              )
            ],
            if(authType.value == '2')...[
              Column(
                children: [
                  SizedBox(height: 50.h,),
                  Text("身份证认证",style: TextStyle(color: Colors.blueAccent,fontSize: 16.sp,fontWeight: FontWeight.bold),),
                  SizedBox(height: 5.h,),
                  Text("请在读卡区域放置您的身份卡",style: TextStyle(color: Colors.blueAccent,fontSize: 12.sp,fontWeight: FontWeight.bold),),
                  SizedBox(height: 20.h,),
                  Stack(
                    alignment: AlignmentDirectional.center,
                    children: [
                      Image.asset("assets/images/mode.png",width:150.w,fit: BoxFit.fitWidth,),
                      Positioned(
                        top: 220.h,
                        right: 0,
                        child: Image.asset("assets/images/card.png",width:60.w,fit: BoxFit.fitWidth,),
                      )
                    ],
                  )
                ],
              )
            ],
            if(authType.value == '3')...[
              Obx(() => Column(
                children: [
                  SizedBox(height: 50.h,),
                  Text("人脸认证",style: TextStyle(color: Colors.blueAccent,fontSize: 16.sp,fontWeight: FontWeight.bold),),
                  SizedBox(height: 5.h,),
                  Text("请注视屏幕上方摄像头",style: TextStyle(color: Colors.blueAccent,fontSize: 12.sp,fontWeight: FontWeight.bold),),
                  SizedBox(height: 30.h,),
                  if(camera.cameraId.value > 0)...[
                    RepaintBoundary(
                      key: _globalKey,
                      child:  ClipOval(
                        clipper: AuthClipperOvalPath(),
                        child:  Transform.scale(
                          scale:settingEntity.scale1??1,
                          child: Transform.translate(offset: Offset((settingEntity.translateX1??0).w,(settingEntity.translateY1??-100).h),
                            child: RotatedBox(
                              quarterTurns: settingEntity.rotate??0,
                              child: AspectRatio(
                                  aspectRatio: camera.getPreviewSize(),
                                  child: CameraPlatform.instance.buildPreview(camera.cameraId.value)
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),
                    // SizedBox(height: 5.h,),
                    // Text("请注视屏幕下方摄像头",style: TextStyle(color: Colors.blueAccent,fontSize: 12.sp,fontWeight: FontWeight.bold),),
                  ]
                ],
              ))
            ],
            if(authType.value == '4')...[
              Column(
                children: [
                  SizedBox(height: 50.h,),
                  Text("二维码认证",style: TextStyle(color: Colors.blueAccent,fontSize: 16.sp,fontWeight: FontWeight.bold),),
                  SizedBox(height: 5.h,),
                  Text("请在扫码区域扫描您的二维码",style: TextStyle(color: Colors.blueAccent,fontSize: 12.sp,fontWeight: FontWeight.bold),),
                  SizedBox(height: 20.h,),
                  Image.asset("assets/images/qr_mode.png",width:200.w,fit: BoxFit.fitWidth,),
                  Container(
                    width: 200.w,
                    height: 20.h,
                    margin: EdgeInsets.all(5.r),
                    child: TextField(
                      keyboardType: TextInputType.number,
                      decoration:  InputDecoration(
                        hintText: '输入读者号',
                        border:  const OutlineInputBorder(),
                        contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 0, bottom: 0).r,
                      ),
                      style: TextStyle(fontSize: 8.sp),
                      onSubmitted: (value) {
                        eventFactory.fire(UserIdEvent(value));
                      },
                    ),
                  ),
                ],
              )
            ],

          ]),
    ));
  }

  show32({int height = 620,int marginTop = 150,int buttonMarginTop = 50}){
    if( authType.value == '0'){
      authType.value = settingEntity.auth!.substring(0,1);
    }
    _onTap(authType.value);
    return Obx(() => Container(
      margin: EdgeInsets.only(top: 10.h,left: 16.w,right: 16.w,bottom: 10.h),
      padding: EdgeInsets.all(30.r),
      width: double.infinity,
      height: height.h,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.all(Radius.circular(4.r)),
      ),
      child: Stack(
          alignment: AlignmentDirectional.center,
          children: [
            if(authType.value == '1')...[
              Column(
                children: [
                  SizedBox(height: marginTop.h,),
                  Text("读者卡认证",style: TextStyle(color: Colors.blueAccent,fontSize: 16.sp,fontWeight: FontWeight.bold),),
                  SizedBox(height: 5.h,),
                  Text("请在读卡区域放置您的读者卡",style: TextStyle(color: Colors.blueAccent,fontSize: 12.sp,fontWeight: FontWeight.bold),),
                  SizedBox(height: 20.h,),
                  Stack(
                    alignment: AlignmentDirectional.center,
                    children: [
                      Image.asset("assets/images/mode.png",width:150.w,fit: BoxFit.fitWidth,),
                      Positioned(
                        top: 220.h,
                        right: 0,
                        child: Image.asset("assets/images/reader_mode.png",width:70.w,fit: BoxFit.fitWidth,),
                      )
                    ],
                  )
                ],
              )
            ],
            if(authType.value == '2')...[
              Column(
                children: [
                  SizedBox(height: marginTop.h,),
                  Text("身份证认证",style: TextStyle(color: Colors.blueAccent,fontSize: 16.sp,fontWeight: FontWeight.bold),),
                  SizedBox(height: 5.h,),
                  Text("请在读卡区域放置您的身份卡",style: TextStyle(color: Colors.blueAccent,fontSize: 12.sp,fontWeight: FontWeight.bold),),
                  SizedBox(height: 20.h,),
                  Stack(
                    alignment: AlignmentDirectional.center,
                    children: [
                      Image.asset("assets/images/mode.png",width:150.w,fit: BoxFit.fitWidth,),
                      Positioned(
                        top: 220.h,
                        right: 0,
                        child: Image.asset("assets/images/card.png",width:60.w,fit: BoxFit.fitWidth,),
                      )
                    ],
                  )
                ],
              )
            ],
            if(authType.value == '3')...[
              Obx(() => Column(
                children: [
                  SizedBox(height: marginTop.h,),
                  Text("人脸认证",style: TextStyle(color: Colors.blueAccent,fontSize: 16.sp,fontWeight: FontWeight.bold),),
                  SizedBox(height: 5.h,),
                  Text("请注视屏幕下方摄像头",style: TextStyle(color: Colors.blueAccent,fontSize: 12.sp,fontWeight: FontWeight.bold),),
                  SizedBox(height: 30.h,),
                  Icon(Icons.arrow_downward,size: 80.sp,color: Colors.blueAccent,),
                  SizedBox(height: 30.h,),
                  if(camera.cameraId.value > 0)...[
                    RepaintBoundary(
                      key: _globalKey,
                      child:  ClipOval(
                        clipper: AuthClipperOvalPath(),
                        child:  Transform.scale(
                          scale:settingEntity.scale1??1,
                          child: Transform.translate(offset: Offset((settingEntity.translateX1??0).w,(settingEntity.translateY1??-100).h),
                            child: RotatedBox(
                              quarterTurns: settingEntity.rotate??0,
                              child: AspectRatio(
                                  aspectRatio: camera.getPreviewSize(),
                                  child: CameraPlatform.instance.buildPreview(camera.cameraId.value)
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),
                    // SizedBox(height: 5.h,),
                    // Text("请注视屏幕下方摄像头",style: TextStyle(color: Colors.blueAccent,fontSize: 12.sp,fontWeight: FontWeight.bold),),
                  ]
                ],
              ))
            ],
            if(authType.value == '4')...[
              Column(
                children: [
                  SizedBox(height: marginTop.h,),
                  Text("二维码认证",style: TextStyle(color: Colors.blueAccent,fontSize: 16.sp,fontWeight: FontWeight.bold),),
                  SizedBox(height: 5.h,),
                  Text("请在扫码区域扫描您的二维码",style: TextStyle(color: Colors.blueAccent,fontSize: 12.sp,fontWeight: FontWeight.bold),),
                  SizedBox(height: 20.h,),
                  Image.asset("assets/images/qr_mode.png",width:200.w,fit: BoxFit.fitWidth,),
                  Container(
                    width: 200.w,
                    height: 20.h,
                    margin: EdgeInsets.all(5.r),
                    child: TextField(
                      keyboardType: TextInputType.number,
                      decoration:  InputDecoration(
                        hintText: '输入读者号',
                        border:  const OutlineInputBorder(),
                        contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 0, bottom: 0).r,
                      ),
                      style: TextStyle(fontSize: 8.sp),
                      onSubmitted: (value) {
                        eventFactory.fire(UserIdEvent(value));
                      },
                    ),
                  ),
                ],
              )
            ],
            Positioned(
                top: buttonMarginTop.h,
                child:  Row(
                  children: [
                    if(auth.contains('1'))...[
                      Padding(
                          padding: EdgeInsets.only(left: 10.w,right: 10.w),
                          child: InkWell(
                              onTap: (){
                                if(authType.value != '1'){
                                  _onTap('1');
                                }
                              },
                              child: Image.asset("assets/images/${authType.value == '1'?'reader_select':'reader_unselect'}.png",width:50.w,fit: BoxFit.fitWidth,)
                          )
                      )
                    ],
                    if(auth.contains('2'))...[
                      Padding(
                          padding: EdgeInsets.only(left: 10.w,right: 10.w),
                          child: InkWell(
                              onTap: (){
                                if(authType.value != '2'){
                                  _onTap('2');
                                }
                              },
                              child: Image.asset("assets/images/${authType.value == '2'?'id_select':'id_unselect'}.png",width:50.w,fit: BoxFit.fitWidth,)
                          )
                      )
                    ],
                    if(auth.contains('3'))...[
                      Padding(
                          padding: EdgeInsets.only(left: 10.w,right: 10.w),
                          child: InkWell(
                              onTap: (){
                                if(authType.value != '3'){
                                  _onTap('3');
                                }
                              },
                              child: Image.asset("assets/images/${authType.value == '3'?'face_select':'face_unselect'}.png",width:50.w,fit: BoxFit.fitWidth,)
                          )
                      )
                    ],
                    if(auth.contains('4'))...[
                      Padding(
                          padding: EdgeInsets.only(left: 10.w,right: 10.w),
                          child: InkWell(
                              onTap: (){
                                if(authType.value != '4'){
                                  _onTap('4');
                                }
                              },
                              child: Image.asset("assets/images/${authType.value == '4'?'qr_select':'qr_unselect'}.png",width:50.w,fit: BoxFit.fitWidth,)
                          )
                      )
                    ]
                  ],
                )
            )
          ]),
      ));
    }

  _onTap(tap) async {
    camera.stop();
    if(tap == '1'){
      currentTask.authType = 1;
      authType.value = '1';
      tts.speak('请刷读者卡');
      manager.setModeAndStart(Mode.reader);
      // cameraId.value = await camera.disposeCurrentCamera();
    }else if(tap == '2'){
      currentTask.authType = 2;
      authType.value = '2';
      manager.setModeAndStart(Mode.identify);
      tts.speak('请刷身份证');
      // cameraId.value = await camera.disposeCurrentCamera();
    }else if(tap == '3'){
      if(settingEntity.face == 'nt'){
        _getToken();
      }
      currentTask.authType = 3;
      authType.value = '3';
      manager.setModeAndStart(Mode.none);
      tts.speak('请刷人脸');
      if(camera.cameraId.value == -1){
        camera.cameraId.value = await camera.openCamera();
      }
      if(camera.cameraId.value != -1){
        camera.start((){
          if(settingEntity.norms == '32'){
            _widgetToImage();
          }else{
            _computeTakePicture();
          }
        });
      }
    }else{
      currentTask.authType = 4;
      authType.value = '4';
      manager.setModeAndStart(Mode.none);
      tts.speak('请刷二维码');
    }
  }


  final GlobalKey _globalKey = GlobalKey();

  _computeTakePicture() async {
    CameraPlatform.instance.takePicture(camera.cameraId.value).then((XFile file){
       file.readAsBytes().then((bytes){
         String base64 = base64Encode(bytes);
         String base64Image = "data:image/png;base64,$base64";
         _search(base64Image);
         File f = File.fromUri(Uri.file(file.path));
         f.delete();
         // faceSearch(base64Image).then((data){
         //   if(data.$1 != null){
         //     if(currentTask.uid == null){
         //       eventFactory.fire(UserIdEvent(data.$1.userId));
         //       camera.stop();
         //     }
         //   }else{
         //     toastWarn('${data.$2}');
         //   }
         // });

       });

    });

  }

  _widgetToImage() {
    if(_globalKey.currentContext == null){
      camera.stop();
      return;
    }
    RenderRepaintBoundary render = _globalKey.currentContext!.findRenderObject() as RenderRepaintBoundary;
    render.toImage().then((image){
      image.toByteData(format: ui.ImageByteFormat.png).then((byteData){
        if(byteData != null){
          String base64 = base64Encode(byteData.buffer.asUint8List());
          String base64Image = "data:image/png;base64,$base64";

          _search(base64Image);
          // faceSearch(base64Image).then((data){
          //   if(data.$1 != null){
          //     if(currentTask.uid == null){
          //       eventFactory.fire(UserIdEvent(data.$1.userId));
          //       camera.stop();
          //     }
          //   }else{
          //     toastWarn('${data.$2}');
          //   }
          // });
        }
      });
    });
  }

  _search(base64Image){
    if(settingEntity.face == 'nt'){
      ntFaceSearch(base64Image,token).then((data){
        _searchResult(data);
      });
    }else{
      faceSearch(base64Image).then((data){
        _searchResult(data);
      });
    }
  }

  _searchResult(data){
    if(data.$1 != null){
      if(currentTask.uid == null){
        eventFactory.fire(UserIdEvent(data.$1.userId));
        camera.stop();
      }
    }else{
      toastWarn('${data.$2}');
    }
  }

}

